package spring.cloud.eurekaclientproduct.cmd;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandKey.Factory;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.springframework.web.client.RestTemplate;
import com.spring.cloud.commonutils.vo.ResultMessage;
import com.spring.cloud.commonutils.vo.UserInfo;


public class UserGetCommand extends HystrixCommand<UserInfo> {

    private RestTemplate restTemplate;
    private Long id;

    private final static HystrixCommandKey COMMAND_KEY = HystrixCommandKey.Factory.asKey("user_get");
    private final String URL = "http://eureka-client-user/user/info/{id}";

    public UserGetCommand(RestTemplate restTemplate, Long id) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("userGroup")).andCommandKey(COMMAND_KEY));
        this.restTemplate = restTemplate;
        this.id = id;
    }

    @Override
    protected String getCacheKey() {
        return "user_"+id;
    }

    @Override
    protected UserInfo run() throws Exception {
        System.out.println("获取用户"+id);
        return restTemplate.getForObject(URL,UserInfo.class,id);
    }

    public static void clearCache(Long id){
        String cacheKey = "user_"+id;
        HystrixRequestCache.getInstance(COMMAND_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(cacheKey);
    }
}
